<?php

namespace App\Controller\System;

use App\Controller\ApiController;
use Usap\Service\Service;

/**
 *设备接口
 */
class DevicesController extends ApiController
{


    public function init()
    {
        $user_id = $this->context->userId;
        if (empty($user_id)) {
            $this->ajaxReturn(array('code' => -1001, 'code_str' => "请先登录"));
        }
        $place_service = Service::instance()->find('operation', 'place');

        $devices_service = Service::instance()->find('Devices', 'devices');

        $typeconfig = $devices_service->getDeviceTypesConfig();

        $categoryconfi = $devices_service->getDeviceCategoryConfig();

        $placeconfig = $place_service->get_place_config();

        $cycleconfi = Service::instance()->loadConfig('Common', 'device', 'getCheckCycle');

        $data = [];
        foreach ($typeconfig as $key => $value) {
            $res['id'] = $key;
            $res['name'] = $value;
            $data['device_type'][] = $res;
        }
        foreach ($categoryconfi as $key => $value) {
            $res['id'] = $key;
            $res['name'] = $value;
            $data['category'][] = $res;
        }
        foreach ($placeconfig as $key => $value) {
            $res['id'] = $key;
            $res['name'] = $value;
            $data['place'][] = $res;
        }
        foreach ($cycleconfi as $key => $value) {
            $res['id'] = $key;
            $res['name'] = $value;
            $data['cycle'][] = $res;
        }
        $return = array('code' => '0000', 'msg' => '请求成功', 'data' => $data);
        $this->ajaxReturn($return);
    }


    /*安装*/
    public function install()
    {
        $user_id = $this->context->userId;
        if (empty($user_id)) {
            $this->ajaxReturn(array('code' => -1001, 'msg' => "请先登录"));
        }
        $request = I('request.');
        $devices_service = Service::instance()->find('Devices', 'devices');
        $post = [
            'user_id' => 1,
            'name' => $request['name'],
            'codeserial' => $request['codeserial'],
            'device_type' => $request['device_type'],
            'device_category' => $request['device_category'],
            'check_cycle' => $request['check_cycle'],
            'place_id' => $request['place_id'],
            'device_address' => $request['device_address'],
            'position' => $request['position'],
            'manager' => $request['manager'],
            'manager_phone' => $request['manager_phone'],
            'contacts_phone' => $request['contacts_phone'],
        ];

        $result = $devices_service->addDevice($post);
        if ($result['code'] == '0000') {
            $data = [
                'devices_info' => [
                    'device_id' => $result['device_id']
                ]
            ];
            $return = array('code' => '0000', 'msg' => '安装成功', 'data' => $data);
            $this->ajaxReturn($return);
        } else {
            $this->ajaxReturn($result);
        }
    }


    /**
     * 设备状态
     */
    public function actuality()
    {
        $user_id = $this->context->userId;
        \Logger::getLogger('home.user.account')->apps('login_start')->info(I());
        if (empty($user_id)) {
            $this->ajaxReturn(array('code' => -1001, 'code_str' => "请先登录"));
        }
        //定义设备状态 is_standby 1 正常  0 损坏
        $date = date('Y-m-d');
        $devices_service = Service::instance()->find('devices', 'devices');
        $request = I('request.');
        $page = $request['page'] ? $request['page'] : 1;
        $rows = '';
        $order = $request['order'] ? $request['order'] : 'device_id';
        $sort = $request['sort'] ? $request['sort'] : 'asc';
        $type = $request['type'] ? $request['type'] : '';
        $keyword = $request['keyword'] ? $request['keyword'] : '';
        $where = 1;
        if ($type == '1') {
            $where .= " and created_time like '%$date%'";
        } elseif ($type == 2) {
            $where .= " and is_standby = 0";
        } elseif ($type == 3) {
            $where .= " and is_online = 1";
        } elseif ($type == 4) {
            $where .= " and is_online =0";
        }
        if ($keyword) {
            $where .= " and codeserial like '%$keyword%' or device_address like '%$keyword%'";
        }
        $device_list = $devices_service->getDeviceList($where, $page, $rows, $order, $sort);
        $list = [];
        if ($device_list['count'] > 0) {
            $today = 0; //正常个数
            $damage = 0; //损坏个数
            $online = 0; //在线个数
            $downline = 0; //离线
            foreach ($device_list['list'] as $value) {
                if ($value['is_standby'] == 0) {
                    $damage++;
                }
                if ($value['is_online'] == 1) {
                    $online++;
                } elseif ($value['is_online'] == 0) {
                    $downline++;
                }
                if (date('Y-m-d', strtotime($value['created_time'])) == $date) {
                    $today++;
                }
                $res['device_id'] = $value['device_id'];
                $res['is_online'] = $value['is_online'];
                $res['is_standby'] = $value['is_standby'];
                $res['codeserial'] = $value['codeserial'];
                $res['codeserial'] = $value['codeserial'];
                $res['device_address'] = $value['device_address'];
                $list['device_list'][] = $res;
            }
            if (empty($type) && empty($keyword)) {
                $list['today'] = $today;
                $list['damage'] = $damage;
                $list['online'] = $online;
                $list['downline'] = $downline;
                $list['total'] = $device_list['count'];
            }
        }
        $return = array('code' => '0000', 'msg' => '请求成功', 'data' => $list);
        $this->ajaxReturn($return);

    }


    /**
     * 设备信息
     */
    public function device_info()
    {
        $user_id = $this->context->userId;
        \Logger::getLogger('home.user.account')->apps('login_start')->info(I());
        if (empty($user_id)) {
            $this->ajaxReturn(array('code' => -1001, 'msg' => "请先登录"));
        }
        $devices_service = Service::instance()->find('devices', 'devices');
        $alarms_service = Service::instance()->find('common', 'alarms');
        $user_service = Service::instance()->find('account', 'user');

        $device_types_config = $devices_service->getDeviceTypesConfig();
        $device_categroy_config = $devices_service->getDeviceCategoryConfig();
        $request = I('request.');
        $id = $request['id'];
        $device_info = $devices_service->getInfoByDeviceId($id);
        $alarms_info = $alarms_service->getAlarmsInfoByCodeserial($device_info['codeserial']);
        //返回前段信息汇总
        $data['basic_info'] = [
            'codeserial' => $device_info['codeserial'],
            'manager' => $device_info['manager'],
            'manager_phone' => $device_info['manager_phone'],
            'device_type' => $device_types_config[$device_info['device_type']],
            'device_category' => $device_categroy_config[$device_info['device_category']],
        ];
        //获取用户信息
        $user_info = $user_service->getInfoByID($alarms_info['user_id']);
        $data['alarms_info'] = [
            'alarm_date' => $alarms_info['created_time'] ? date('Y-m-d H:i:s', $alarms_info['created_time']) : '',
            'deal_user_name' => $user_info['user_name'] ? $user_info['user_name'] : '',
            'operation_user_name' => '',
            'operation_date' => '',
        ];
        $user_info = $user_service->getInfoByID($device_info['user_id']);
        $data['install_info'] = [
            'user_name' => $user_info['user_name'],
            'created_time' => $device_info['created_time'],
            'device_address' => $device_info['device_address'],
            'position' => $device_info['position'],
        ];
        $return = array('code' => '0000', 'msg' => '请求成功', 'data' => $data);
        $this->ajaxReturn($return);
    }

    /**
     * 巡检任务
     */
    public function check_task()
    {
        $user_id = $this->context->userId;
        \Logger::getLogger('home.user.account')->apps('login_start')->info(I());
        if (empty($user_id)) {
            $this->ajaxReturn(array('code' => -1001, 'msg' => "请先登录"));
        }
        $crontal_service = Service::instance()->find('common', 'crontal');
        $devices_service = Service::instance()->find('devices', 'devices');

        //获取巡检任务
        $where = 'a.user_id =' . $user_id;
        $request = I('request.');
        $page = $request['page'] ? $request['page'] : 1;
        $rows = $request['rows'] ? $request['rows'] : 20;
        $order = $request['order'] ? $request['order'] : 'a.begin_time';
        $sort = $request['sort'] ? $request['sort'] : 'asc';
        $type = $request['state'] ? $request['state'] : 'on';
        $date = date('Y-m-d H:i:s');
        if ($type == 'on') {
            $where .= " and a.status ='1'";
            $where .= " and a.begin_time<='$date' and a.end_time>= '$date' ";
        } else {
            $where .= " and a.status ='2'";
        }
        if ($request['id']) {
            $device_id = $request['id'];
            $where .= " and a.device_id = '$device_id' and a.status !='0'";
        }
        if ($request['keyword']) {
            $keyword = $request['keyword'];
            $where .= " and a.code like '%$keyword%'or a.taskName like '%$keyword%'";
        }
        $crontal_list = $crontal_service->getCheckTaskList($where, $page, $rows, $order, $sort, 'a.*,b.codeserial,b.device_category,c.user_name');
        $device_categroy_config = $devices_service->getDeviceCategoryConfig();
        $list['task_info'] = [];
        if ($crontal_list['count'] > 0) {
            foreach ($crontal_list['list'] as $value) {
                $res['id'] = $value['id'];
                $res['category'] = $device_categroy_config[$value['device_category']];
                $res['code'] = $value['code'];//任务编号
                $res['taskName'] = $value['taskName'];
                $res['begin_time'] = $value['begin_time'];
                $res['end_time'] = $value['end_time'];
                $res['status'] = $value['status'];
                $list['task_info'][] = $res;
            }
        }
        $return = array('code' => '0000', 'msg' => '获取数据成功', 'data' => $list);
        $this->ajaxReturn($return);

    }


    /**
     * 巡检任务处置
     */
    public function deal_task()
    {
        $user_id = $this->context->userId;
        \Logger::getLogger('home.user.account')->apps('login_start')->info(I());
        if (empty($user_id)) {
            $this->ajaxReturn(array('code' => -1001, 'code_str' => "请先登录"));
        }
        $crontal_service = Service::instance()->find('common', 'crontal');
        $request = I('request.');
        $id = $request['id'];
        $remark = $request['remark'];
        //查询对应巡检任务
        $task_info = $crontal_service->getCheckTaskInfoById($id);
        $time = time();
        if (!$task_info) {
            $this->ajaxReturn(array('code' => -404, 'msg' => "任务信息错误"));
        }
        if (strtotime($task_info['begin_time']) - $time > 0) {
            $this->ajaxReturn(array('code' => -10000, 'msg' => "任务还未到开始时间"));
        }
        $data = [
            'status' => 2,
            'checked_time' => date('Y-m-d H:i:s'),
            'remark' => $remark,
        ];
        $device_id = $task_info['device_id'];
        $res = $crontal_service->updateCheckTaskInfo($id, $data, $device_id);
        $info['info'] = [];
        if ($res) {
            $return = array('code' => '0000', 'msg' => '处置成功', 'data' => $info);
            $this->ajaxReturn($return);
        } else {
            $return = array('code' => '-10001', 'msg' => '因系统异常，执行失败', 'data' => $info);
            $this->ajaxReturn($return);
        }
    }

    public function heartbeat()
    {
        $user_id = $this->context->userId;
        \Logger::getLogger('home.user.account')->apps('login_start')->info(I());
        if (empty($user_id)) {
            $this->ajaxReturn(array('code' => -1001, 'code_str' => "请先登录"));
        }
        $devices_service = Service::instance()->find('devices', 'devices');
        $request = I('request.');
        $id = $request['id'];
        $type = $request['type'] ? $request['type'] : 'week';
        if (!$id) {
            $this->ajaxReturn(array('code' => -404, 'msg' => "设备ID不能为空"));
        }
        $where = "device_id = '$id'";
        $startDate = date('Y-m-d');
        $moth = substr($startDate, 0, 7);
        $year = substr($startDate, 0, 4);
        if ($type == 'week') {
            $endDate = date("Y-m-d", (strtotime($request['startDate']) - 7 * 3600));
            $where .= " and created_time <='$startDate' and created_time >='$endDate'";
        } else {
            $where .= " and created_time like '%$moth%'";
        }
        $report_list = $devices_service->getReportListByCondition($where);
        $list['report_info'] = [];
        if ($report_list) {
            $days = [];
            foreach ($report_list as $v) {
                $num = substr($v['created_time'], 8, 2);
                $days[] = $num;
            }
            $day = date('d');
            $day_t = 0;
            if ($day <= 7) {
                $day_t = $day_nums = $this->getMonthLastDay($moth - 1, $year);
            }
            $day_nums = $this->getMonthLastDay($moth, $year);
            if ($type == 'week') {
                if ($day <= 7) {
                    $pr = 7 - $day + 1;
                } else {
                    $pr = 0;
                }
                if ($day < 10) {
                    $day = substr($day, 1, 1);
                }
                if ($day > 7) {
                    for ($i = $day; $i > $day - 7; $i--) {
                        if ($i <= 0) {
                            break;
                        }
                        if ($i < 10) {
                            $i = '0' . $i;
                        }
                        if (in_array($i, $days)) {
                            $res['time'] = $moth . '-' . $i;
                            $res['status'] = 1;
                        } else {
                            $res['time'] = $moth . '-' . $i;
                            $res['status'] = 0;
                        }
                        $list['report_info'][] = $res;
                    }
                } else {
                    for ($i = $day; $i <= $day; $i--) {
                        if ($i <= 0) {
                            break;
                        }
                        if ($i < 10) {
                            $i = '0' . $i;
                        }
                        if (in_array($i, $days)) {
                            $res['time'] = $moth . '-' . $i;
                            $res['status'] = 1;
                        } else {
                            $res['time'] = $moth . '-' . $i;
                            $res['status'] = 0;
                        }
                        $list['report_info'][] = $res;
                    }
                    if ($pr > 0) {
                        $moth = date('Y-m', strtotime('-1 month'));
                        for ($i = $day_t; $i > ($day_t - $pr); $i--) {
                            if ($i < 10) {
                                $i = '0' . $i;
                            }
                            if (in_array($i, $days)) {
                                $res['time'] = $moth . '-' . $i;
                                $res['status'] = 1;
                            } else {
                                $res['time'] = $moth . '-' . $i;
                                $res['status'] = 0;
                            }
                            $list['report_info'][] = $res;
                        }
                    }
                }
            } else {
                for ($i = $day_nums; $i >= 0; $i--) {
                    if ($i <= 0) {
                        break;
                    }
                    if ($i < 10) {
                        $i = '0' . $i;
                    }
                    if (in_array($i, $days)) {
                        $res['time'] = $moth . '-' . $i;
                        $res['status'] = 1;
                    } else {
                        $res['time'] = $moth . '-' . $i;
                        $res['status'] = 0;
                    }
                    $list['report_info'][] = $res;
                }
            }
        }
        $return = array('code' => '0000', 'msg' => '获取数据成功', 'data' => $list);
        $this->ajaxReturn($return);
    }


    public function getMonthLastDay($month, $year)
    {
        switch ($month) {
            case 4 :
            case 6 :
            case 9 :
            case 11 :
                $days = 30;
                break;
            case 2 :
                if ($year % 4 == 0) {
                    if ($year % 100 == 0) {
                        $days = $year % 400 == 0 ? 29 : 28;
                    } else {
                        $days = 29;
                    }
                } else {
                    $days = 28;
                }
                break;
            default :
                $days = 31;
                break;
        }
        return $days;
    }

}
